package com.aliware.tianchi;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Semaphore;
import java.util.concurrent.ThreadLocalRandom;

/**
 * Facade
 */
public class HashServiceImpl implements HashInterface {
    private static final Logger LOGGER = LoggerFactory.getLogger(HashServiceImpl.class);

    private final String salt;
    private final ThrashConfig configs;
    private final Semaphore concurrent;
    private final int maxPermit = 100000;

    HashServiceImpl(String salt, ThrashConfig configs) {
        this.salt = salt;
        this.configs = configs;
        this.concurrent = new Semaphore(maxPermit);
    }

    @Override
    public CompletableFuture<Integer> hash(String input) {
        long st = System.currentTimeMillis();
        try {
            concurrent.acquire();
            int concurrent = maxPermit - this.concurrent.availablePermits();
            long rtt = (long) (Math.pow(configs.index, concurrent) * ThreadLocalRandom.current().nextDouble());
            if (rtt > 5000) {
                Thread.sleep(5000);
            } else {
                Thread.sleep(rtt);
            }
            int hashCode = (input + salt).hashCode();
            LOGGER.info("请求处理："+hashCode);
            return CompletableFuture.completedFuture(hashCode);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        } finally {
            long cost = System.currentTimeMillis() - st;
            LOGGER.info("HashService cost:{} ms to handle request", cost);
            concurrent.release();
        }
        throw new IllegalStateException("Unexpected exception");
    }
}
